<?php
class App_File
{	
	protected $_msg = '';
	protected $_allow = array('.jpg','.jpeg','.png','.gif','.flv', '.txt');
	protected $_dir = '';
	
	public function upload($file, $dir)
	{
		$this->_dir = $dir . '/';		
		
		if (!file_exists($this->_dir)) {
			if (!mkdir($this->_dir, 0777)) {
				$this->_msg = '文件夹创建失败';
				return false;
			}
		}
		
		if (!$this->isAllow($file['name'])) {
			$this->_msg = '不允许上传该类型文件';
			return false;
		}		
		$fileName = $this->getFilename($this->checkType($file['name']));        
        $targetName = $this->_dir . $fileName;  
        

        if ($this->uploadFile($file['tmp_name'], $targetName)) {        	
        	return str_replace(_WEB_DIR_, '', $targetName);
        } else {
        	$this->_msg = '文件上传失败';
        	return false;
        }			
	}
	
	public function msg()
	{
		return $this->_msg;
	}
	
	public function checkType($path)
	{
	    $pos = strrpos($path, '.');
        if ($pos !== false) {
            return strtolower(substr($path, $pos));
        } else {
            return '';
        }
	}
	
	public function isAllow($path)
	{
		if (!in_array($this->checkType($path), $this->_allow)) {
			return false;
		} else {
			return true;
		}
	}
	
	public function getFilename($type)
	{
		$fileName = time().rand(10,99) . $type;
		if (file_exists($this->_dir.$type)) {
			return $this->getFilename($type);
		} else {
			return $fileName;
		}
	}
	
	public function uploadFile($file, $targetName) 
	{
	    if (isset($file['error']) && $file['error'] > 0){
            return false;
        }
		if (function_exists("move_uploaded_file")){
            if (move_uploaded_file($file, $targetName)){
                @chmod($targetName,0755);
                return true;
            } else if (copy($file, $targetName)){
                @chmod($targetName,0755);
                return true;
            }
        } elseif (copy($file, $targetName)) {
            @chmod($target_name,0755);
            return true;
        }
        return false;
	}
}